// Hercules.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "Hercules.h"


#ifdef _MANAGED
#pragma managed(push, off)
#endif

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
    return TRUE;
}

#ifdef _MANAGED
#pragma managed(pop)
#endif

// This is an example of an exported variable
//HERCULES_API int nHercules=0;

// This is an example of an exported function.
HERCULES_API int fnHercules(void)
{
	return 42;
}

// This is the constructor of a class that has been exported.
// see Hercules.h for the class definition
CHercules::CHercules()
{
	m_pPath = new TCHAR[MAX_PATH];
	return;
}

CHercules::~CHercules()
{
	if (NULL != m_pPath)
	{
		delete m_pPath;
		m_pPath = NULL;
	}
	return;
}

int CHercules::SetFilePath(TCHAR* pPath)
{
	wcscpy(m_pPath, pPath);
	return 0;
}

int CHercules::WriteStringToFile( TCHAR* pChar )
{
	ofstream file;
	file.open( m_pPath, ios_base::app);
	int nLen = WideCharToMultiByte(CP_ACP, NULL, pChar, -1, NULL, NULL, NULL, FALSE );
	char* tempbuf = new char[nLen];
	WideCharToMultiByte(CP_ACP, NULL, pChar, -1, tempbuf, nLen, NULL, FALSE );
	
	//file.write(pchBuffer, dwLen+1);
	file<<tempbuf<<endl;

	delete[] tempbuf;
	tempbuf = NULL;
	file.close();
	return 0;
}

int CHercules::ReadDataFromFile(TCHAR* pChar, int nBufLength)
{
	ifstream file;
	int nRtn = nBufLength;
	char* tempbuf = new char[nBufLength + 2];
	char* buf = tempbuf;
	file.open(m_pPath, ios_base::in);
	if (!file)
	{
		return -1;
	}
	
	//file.get(tempbuf, nBufLength);
	char cTemp = '\0';
	while (nRtn && file.get(cTemp))
	{
		*(buf++) = cTemp;
		*(buf+1) = '\0';
		nRtn--;
	}
	int nLen = strlen(tempbuf) + 1;
	int nwLen = MultiByteToWideChar(CP_ACP, 0, tempbuf, nLen, NULL, 0); 
	MultiByteToWideChar(CP_ACP, 0, tempbuf, nLen, pChar, nwLen);

	delete[] tempbuf;
	tempbuf = NULL;
	if (file.eof())
	{
		nRtn = nwLen;
	}
	file.close();
	return nRtn;
}